<script setup>
import {
  Edit,
  Delete, Search, OfficeBuilding
} from '@element-plus/icons-vue'
import { onMounted, ref } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { addHotelService, deleteHotelService, getHotelsService, updateHotelService } from "@/api/hotel.js";

//显示弹窗
const dialogVisible = ref(false);
//分页条数据模型
const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(3)//每页条数
//导入token
import { useTokenStore } from '@/stores/token.js';
import router from "@/router/index.js";
const tokenStore = useTokenStore();

//酒店列表数据模型
const hotels = ref([
  {
    "hotelName": "string",
    "isStared": -2147483648,
    "popularity": -2147483648,
    "image": "string",
    "email": "string",
    "phoneNumber": "string",
    "location": "string",
  }
])

//搜索输入
const input = ref();
// 选中的数据项
const selectedItems = ref([]);
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const hotelModel = ref({})

//重置酒店模型
const getDefaultHotelModel = () => ({
  hotelName: '',
  isStared: 0,
  popularity: '',
  image: '', // 初始化为空
});

//获取酒店数据
const getHotels = async () => {
  try {
    let result = await getHotelsService();
    //将数据存储，用于渲染视图
    hotels.value = result.data;
    //更新总条数，用于分页显示
    total.value = result.data.length;
    hotels.value = result.data;
  } catch (error) {
    ElMessage({ type: "error", message: "获取列表失败", });
  }
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  //刷新列表
  getHotels();
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num
  //刷新列表
  getHotels();
}

//上传成功,回调函数
const uploadSuccess = (response, file, fileList) => {
  if (response || response.status === 200) {
    // 检查服务端返回的数据结构，确认是否有 fileUrl 字段
    console.log(response);
    
    const fileUrl = response;
    console.log(fileUrl);

    if (fileUrl) {
      // 更新 hotelModel.image，用于显示上传的图片预览
      hotelModel.value.image = fileUrl;
      ElMessage.success('文件上传成功');
    } else {
      ElMessage.error('文件上传失败：未找到文件路径');
    }
  } else {
    ElMessage.error('文件上传失败');
    console.log(response);
    console.log(response.data);
  }
};

//添加酒店
const addHotel = async () => {
  try {
    //调用接口
    let result = await addHotelService(hotelModel.value);
    if (result.code === 0) {
      ElMessage.success(result.message || '添加成功');
    } else {
      ElMessage.error(result.message || '添加失败');
    }
    //酒店模型置空
    hotelModel.value = getDefaultHotelModel();
    //让抽屉消失
    visibleDrawer.value = false;
    //刷新当前列表
    await getHotels();
  } catch (error) {
    console.error('添加酒店时出错：', error);
    ElMessage.error('添加酒店时出错，请重试');
    //让抽屉消失
    visibleDrawer.value = false;
  }
}

//取消添加酒店
const cancel = async () => {
  //酒店数据模型置空
  hotelModel.value = getDefaultHotelModel();
  //让抽屉消失
  visibleDrawer.value = false;
}

//模糊搜索
const inputSearch = async () => {
  const keyword = input.value.trim(); // 转换为小写并去除首尾空格
  if (!keyword) {
    await getHotels(); // 如果搜索关键词为空，则显示所有酒店列表
    return; // 如果搜索关键词为空，直接返回，不执行后续操作
  }
  let result = await getHotels(); // 获取酒店列表
  try {
    let result = await getHotelsService();
    // 根据酒店名进行模糊搜索
    total.value = result.data.filter(hotel =>
      hotel.hotelName.includes(keyword)
    ).length;
    hotels.value = result.data.filter(hotel =>
      hotel.hotelName.includes(keyword)
    );
  } catch (error) {
    console.error('搜索酒店时出错：', error);
    ElMessage({ type: "error", message: "搜索酒店出错", });
  }
  input.value = ''; // 清空输入框
};

//批量删除
// 处理选中事件
const handleSelectionChange = (selected) => {
  selectedItems.value = selected;
};
// 删除选中项
const deleteSelectedComments = () => {
  if (!Array.isArray(selectedItems.value) || selectedItems.value.length === 0) {
    ElMessage({ type: "info", message: "请先选择要删除的项", });
    return;
  }
  ElMessageBox.confirm("确认删除选中的项吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      // 调用后端删除数据的函数
      for (let i = 0; i < selectedItems.value.length; i++) {
        await deleteHotelService(selectedItems.value[i].hotelName);
      }
      // 清空选中项
      selectedItems.value = [];
      //刷新列表
      await getHotels();
      ElMessage({ type: "success", message: "删除成功", });
    })
    .catch(() => {
      ElMessage({ type: "info", message: "删除已取消", });
    });
};

//删除单个酒店
const deleteHotel = (row) => {
  ElMessageBox.confirm("确认删除该酒店吗?", "温馨提示", {
    confirmButtonText: "确认",
    cancelButtonText: "我再想想",
    type: "warning",
  }).then(async () => {
    //调用接口
    let result = await deleteHotelService(row.hotelName);
    if (result.code === 0) {
      ElMessage.success(result.message || '删除成功');
    } else {
      ElMessage.error(result.message || '删除失败');
    }
    await getHotels();
  }).catch(() => {
    ElMessage({ type: "info", message: "删除已取消", });
  })
};

//修改酒店信息
//显示
const handleOpen = async (row) => {
  dialogVisible.value = true
  //获取编辑酒店
  hotelModel.value = row;
}
const editHotel = async () => {
  //编辑酒店
  try {
    let result = await updateHotelService(hotelModel.value);
    if (result.code === 0) {
      ElMessage.success(result.message || '修改成功');
    } else {
      ElMessage.error(result.message || '修改失败');
    }
    dialogVisible.value = false;
  } catch (error) {
    console.error('编辑酒店时出错：', error);
    ElMessage.error('编辑酒店时出错，请重试');
  }
}

//跳往酒店房间管理页面
const goToHotelRoom = (row) => {
  //跳转页面
  router.push({ path: '/room', query: { hotelName: row.hotelName } });
}

//弹窗关闭
const handleClose = () => {
  //酒店模型置空
  hotelModel.value = getDefaultHotelModel();
  //弹窗关闭
  dialogVisible.value = false;
}

onMounted(() => {
  getHotels();
})
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>酒店管理</span>
        <div class="extra">
          <el-button type="primary" @click="visibleDrawer = true">添加酒店</el-button>
        </div>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item>
        <el-input v-model="input" style="width: 240px" placeholder="请输入酒店名" clearabl :prefix-icon="Search" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="inputSearch">搜索</el-button>
        <el-button @click="deleteSelectedComments">批量删除</el-button>
      </el-form-item>
    </el-form>

    <!-- 酒店列表 -->
    <el-table ref="multipleTableRef" :data="hotels.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
      style="width: 100%" @selection-change="handleSelectionChange" :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ 'text-align': 'center' }">
      <el-table-column type="selection" width="55" />
      <el-table-column label="酒店名称" width="100" prop="hotelName"></el-table-column>
      <el-table-column label="酒店星级" prop="isStared"></el-table-column>
      <el-table-column label="酒店人气" prop="popularity"></el-table-column>
      <el-table-column label="邮箱" prop="email"></el-table-column>
      <el-table-column label="电话号码" prop="phoneNumber"></el-table-column>
      <el-table-column label="地址" prop="location"></el-table-column>
      <el-table-column label="房间管理" width="100">
        <template #default="{ row }">
          <el-button :icon="OfficeBuilding" circle plain type="primary" @click="goToHotelRoom(row)"></el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="handleOpen(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteHotel(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
      @current-change="onCurrentChange" style="margin-top: 20px;
        justify-content: flex-end" />

    <!-- 抽屉 -->
    <el-drawer v-model="visibleDrawer" title="添加酒店" direction="rtl" size="50%">
      <!-- 添加酒店表单 -->
      <el-form :model="hotelModel" label-width="100px">
        <el-form-item label="酒店名称">
          <el-input v-model="hotelModel.hotelName" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="hotelModel.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="hotelModel.phoneNumber" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="hotelModel.location" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="人气" prop="phone">
          <el-input v-model="hotelModel.popularity" minlength="1" maxlength="55"></el-input>
        </el-form-item>
        <el-form-item label="酒店封面">
          <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false" action="/api/fileUpload"
            name="file" :headers="{ 'Authorization': tokenStore.token }" :on-success="uploadSuccess">
            <img v-if="hotelModel.image" :src="hotelModel.image" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="酒店简介">
          <div class="editor">
            <quill-editor theme="snow" v-model:content="hotelModel.description" contentType="text">
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addHotel">添加</el-button>
          <el-button type="info" @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 编辑酒店弹窗 -->
    <el-dialog v-model="dialogVisible" title="编辑酒店信息" width="40%">
      <el-form ref="hotelForm" :model="hotelModel" label-width="100px" style="padding-right: 30px">
        <el-form-item label="酒店名称" prop="hotelName">
          <el-input v-model="hotelModel.hotelName" minlength="1" maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="hotelModel.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input v-model="hotelModel.phoneNumber" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="hotelModel.location" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="酒店星级" prop="isStared">
          <el-input v-model="hotelModel.isStared" minlength="1" maxlength="55"></el-input>
        </el-form-item>
        <el-form-item label="酒店人气" prop="popularity">
          <el-input v-model="hotelModel.popularity" minlength="1" maxlength="55"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="editHotel">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>